import React, { Component } from 'react'
import './index.less';
import axios from 'axios'
import Header from '@/components/Header';
import history from '@/history';
import { Form, Popconfirm, Input, Button, message, Modal, AutoComplete, Icon } from 'antd';
import Footer from '@/components/Footer';
import Error from '@/views/components/error';

import utils from '@/utils/utils'
import QRCode from 'qrcode.react';
import store from '@/store'


var timer = null
const Option = AutoComplete.Option;

class searchFn extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showLogin: false,
      showRegister: false,
      isLogin: store.getState().user.isLogin,
      size: 250,
      qrcode: 'https://jskp.jss.com.cn/k.action?kpdm=NUONUO',
      isedit: false,
      form: {
        ckpname: '浙江诺诺网科技有限公司',
        ckpcode: '91330106MA2AYNWD8M',
        ckpaddr: '浙江省杭州市西湖区双龙街100号杭政储出【2013】51号地块商业商务用房5#7层701-708室超出换行超出换行',
        ckptel: '057187138798',
        caccountBlank: '中国工商银行股份有限公司杭州古墩路支行',
        cbankAccount: '1202224909900******',
      },
      dlgTipTxt: '获取验证码',
      msgYzmdis: false,
      seconds: 59,
      hasData: true,
      status: true,
      kpdm: 'NUONUO',
      kpcode: '',
      dataSource: [],
      key: ''
    }


    this.getMsgCode = this.getMsgCode.bind(this);

    this.edit = this.edit.bind(this);//进入到modal搜索


  }

  componentDidMount() {
    //监听登录状态
    this.cancelSubscribe = store.subscribe(() => {
      const state = store.getState()
      if (state.user.isLogin !== this.state.isLogin) {
        this.setState({
          isLogin: state.user.isLogin
        })
      }

      if (!this.state.showLogin) {
        this.setState({
          showLogin: state.user.showLogin
        })
      }
    })


    let urlGet = utils.GetRequest();
    // console.log(urlGet.hasData)
    if (urlGet.hasData === 'false') {
      this.setState({
        hasData: false
      })
    } else {
      if (urlGet.kpdm) {
        this.setState({
          kpdm: urlGet.kpdm,
        })
        this.getCodeInfo(urlGet.kpdm)
      } else if (urlGet.kpcode) {
        this.setState({
          kpcode: urlGet.kpcode,
        })
        this.getKpCodeInfo(urlGet.kpcode)
      }

    }
    // this.getQRCode('https://jskp.jss.com.cn/k.action?kpdm=NUONUO');
  }


  // 卸载store监听
  componentWillUnmount() {
    this.cancelSubscribe()
  }

  getCodeInfo(val) {
    // console.log(val, 'getCodeInfo');
    window.location.href = window.location.origin + window.location.pathname + '#/search?kpdm=' + val;
    axios.get('/nuonuo/invoice/wx/jskpCardNew/getKpinfoNew.action', { params: { qarcode: val } })
      .then(res => {
        // console.log(res)
        if (res.code === 'S0000') {
          this.setState({
            kpdm: res.result.kpInfo.barcode,
            key: res.result.kpInfo.ckpname
          }, () => {
            this.getQRCode();
          });
          this.setState({
            kpdm: res.result.kpInfo.barcode,
            form: res.result.kpInfo,
          })
        }
      })

  }
  getKpCodeInfo(val) {
    // console.log(val, 'getKpCodeInfo');
    window.location.href = window.location.origin + window.location.pathname + '#/search?kpcode=' + val;
    axios.get('/nuonuo/invoice/wx/jskpCardNew/getKpinfoNew.action', { params: { taxnum: val } })
      .then(res => {
        // console.log(res)
        if (res.code === 'S0000') {
          // console.log(res.result.kpInfo.barcode)
          this.setState({
            kpdm: res.result.kpInfo.barcode,
            key: res.result.kpInfo.ckpname
          }, () => {
            this.getQRCode();
          });
          this.setState({
            form: res.result.kpInfo
          })
        }
      })

  }

  // 显示生成 二维码
  getQRCode() {
    // console.log(this.state.kpdm);
    const value = 'https://jskp.jss.com.cn/k.action?kpdm=' + this.state.kpdm
    this.setState({
      qrcode: value
    })
  }

  // 点击编辑
  edit(s) {
    this.setState({ isedit: s })
  }
  cancelEdit() {
    this.setState({ isedit: false })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // console.log('Received values of form: ', values);

        let kpinfo = {
          CKpname: values.ckpname,
          CKpaddr: values.ckpaddr,
          CKptel: values.ckptel,
          CAccountBlank: values.caccountBlank,
          CBankAccount: values.cbankAccount,
          barcode: this.state.kpdm,
          CKpcode: values.ckpcode,
          phonenum: values.phone,
          smsCode: values.yzmCode.replace(/\s+/g, "")
        }

        this.userUpdate(kpinfo);
        // axios.get('/nuonuo/invoice/smsValidate.action', {
        //   params: {
        //     smsCode: values.yzmCode.replace(/\s+/g, ""),
        //     phone: values.phone
        //   }
        // })
        //   .then(res => {
        //     // console.log(res)
        //     if (res.result) {

        //     } else {
        //       message.error('短信验证码不正确')
        //     }
        //   })
      } else {
        // console.log(err, typeof err,Object.entries(err))
        let msg = []

        for (let [k, v] of Object.entries(err)) {
          console.log(k)
          msg.push(Object.values(v.errors)[0].message)
        }
        // console.log(msg)
        message.error(msg[0])
      }
    });
  }
  userUpdate(kpinfo) {
    axios.post('/nuonuo/invoice/wx/jskpCard/updateKpInfoByWeixin.action', { smsCode: kpinfo.smsCode, CKpname: kpinfo.CKpname, CKpaddr: kpinfo.CKpaddr, CKptel: kpinfo.CKptel, CAccountBlank: kpinfo.CAccountBlank, CBankAccount: kpinfo.CBankAccount, barcode: kpinfo.barcode, CKpcode: kpinfo.CKpcode, phonenum: kpinfo.phonenum })
      .then(res => {
        // console.log(res);
        if (res.code === 'S0000') {
          // 接口验证通过
          Modal.success({
            title: '提交审核成功',
            content: '您提交的企业开票信息变更已提交至后台进行审核，请耐心等待~',
            okText: '知道了',
            onOk: () => {
              this.setState({
                isedit: false
              })
            }
          });
        } else if (res.code === 'S0102') {
          message.error(res.describe)
        } else {
          message.error('更新失败')
        }
      })
  }
  // 获取 验证码
  getMsgCode() {
    if (this.state.msgYzmdis) return false;
    // console.log(this.props.form)
    this.props.form.validateFields(['phone'], { force: true }, (err, val) => {
      if (!err) {
        axios.post('/nuonuo/invoice/smsSend.action', val)
          .then(res => {
            // console.log(res);
            if (res.result === "1") {
              this.countDown();
              message.success(res.describe)

            } else {
              message.error(res.describe)
            }
          })
      } else {
        let msg = []
        for (let [k, v] of Object.entries(err)) {
          console.log(k)
          msg.push(Object.values(v.errors)[0].message)
        }
        // console.log(msg)
        message.error(msg[0])
      }
    })
  }
  // 读秒
  countDown() {
    let siv = setInterval(() => {
      this.setState((preState) => ({
        seconds: preState.seconds - 1,
        dlgTipTxt: `${preState.seconds - 1}S`,
        msgYzmdis: true
      }), () => {
        if (this.state.seconds === 0) {
          clearInterval(siv);
          this.setState({
            dlgTipTxt: "获取验证码",
            seconds: 59,
            msgYzmdis: false
          })
        }
      });
    }, 1000)
  }

  onFocus() {
    this.setState({
      dataSource: []
    })
  }

  searchBmjc(val) {
    var keylast = utils.stripscript(val)
    var key = keylast.replace(/\s+/g, "")
    // console.log(key)
    this.setState({
      key: key
    })
    clearTimeout(timer);
    const that = this;
    timer = setTimeout(function () {
      if (key && /^[A-Za-z0-9]{6}$/g.test(key)) {
        // 六位开票代码
        that.getCodeList(key, 0);
      } else if (/[\u4e00-\u9fa5]+/i.test(key) && key.length > 1) {
        // 文字检索
        that.getCodeTextList(key, 0);
      } else {
        that.setState({
          dataSource: []
        })
      }
    }, 200)
  }
  getCodeList(val, type) {
    window._hmt.push(["_trackEvent", `bcard_search_code`, "click", `详情页通过六位代码搜索`]);
    axios.get('/nuonuo/invoice/base/commonInvoice/getkpinfobycode.action', {
      params: {
        intr: val
      }
    }).then(res => {
      if (res.code === 'S0000') {
        if (res.result !== null) {
          // console.log(res.result)
          let TEMP_APPX = {};
          TEMP_APPX.c_code = res.result.barcode
          TEMP_APPX.c_kpcode = res.result.ckpcode
          TEMP_APPX.c_kpname = res.result.ckpname
          TEMP_APPX.signid = res.result.signid
          TEMP_APPX.isCode = 'true'
          if (type === 1) {
            this.getKpCodeInfo(res.result.ckpcode)
            return false;
          }
          this.setState({
            dataSource: [TEMP_APPX],
            key: res.result.ckpname
          })
          // console.log(this.state.key, '-**-')
        } else {
          if (type === 1) {
            this.jump();
            return false;
          }
          message.warning('获取数据异常，稍后再试')
        }
      } else if (res.code === 'S01') {
        message.warning('请登录后进行搜索操作')
      } else {
        // message.warning('未搜索到')
        this.setState({
          dataSource: []
        })
        if (type === 1) {
          this.jump();
          return false;
        }
      }

    })
  }
  getCodeTextList(val, type) {
    window._hmt.push(["_trackEvent", `bcard_search_text`, "click", `详情页通过模糊匹配搜索`]);
    axios.post('/nuonuo/invoice/base/commonInvoice/login/findInvoiceInfo.action', { intr: val })
      .then(res => {
        if (res.code === 'S0000') {

          if (res.result !== null) {
            if (type === 1) {
              this.getCodeInfo(res.result[0].c_code)
              return false;
            }

            this.setState({
              dataSource: res.result
            })

          } else {
            // message.warning('未搜索到数据');
            if (type === 1) {
              this.jump();
              return false;
            }
            this.setState({
              dataSource: []
            })
          }
        } else {
          this.setState({
            dataSource: []
          })
          if (res.result === 'S0105') {
            message.warning('请登录后进行搜索操作');
            this.setState({
              dataSource: []
            })
          } else {
            message.warning('获取数据异常，稍后再试')
          }
        }
      })
  }
  onSelect(value, option) {
    // console.log('onSelect', value, option.props, option.props.type);
    this.getQRCode();
    this.setState({
      hasData: true
    })

    if (option.props.type) {
      window._hmt.push(["_trackEvent", `bcard_search_select`, "click", `详情页用户点击备选搜索`]);
      this.getKpCodeInfo(option.props.kpcode)
    } else {
      window._hmt.push(["_trackEvent", `bcard_search_select`, "click", `详情页用户点击备选搜索`]);
      this.getCodeInfo(value)
    }
  }
  jump(kpdm, cpcode) {
    this.setState({
      hasData: false
    })
    history.push({
      // pathname: '/Contents/pages/BCard/index.html/search',
      pathname: 'search',
      search: '?hasData=false'
    })
  }
  onSearch(key) {
    // console.log('onSearch', value);
    if (key && /^[A-Za-z0-9]{6}$/g.test(key)) {
      // 六位开票代码
      this.getCodeList(key, 1);
      window._hmt.push(["_trackEvent", `bcard_search`, "click", `详情页用户点击搜索`]);
    } else if (key.length > 1) {
      // 文字检索
      this.getCodeTextList(key, 1);
      window._hmt.push(["_trackEvent", `bcard_search`, "click", `详情页用户点击搜索`]);
    } else {
      this.setState({
        dataSource: []
      })
    }

  }
  renderOption(item) {
    // console.log(item)
    return (
      <Option key={item.c_code} signid={item.signid} kpcode={item.c_kpcode} type={item.isCode}>
        <a>
          {item.c_kpname}
        </a>
      </Option>
    );
  }


  render() {
    const { isLogin } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 },
      },
    };
    const { dataSource } = this.state;
    return (
      <div>
        <Header
          isLogin={isLogin}
          className='_relative'
          doLogin={this.doLoginFn}
          doRegister={this.doRegisterFn}
          searchbox={
            <div className='header-search' style={{ width: 360 }}>
              <AutoComplete
                className="global-search"
                style={{ width: '100%' }}
                // value={String(this.state.key)}
                // defaultValue={this.state.key}
                dataSource={dataSource.map(this.renderOption)}
                onSelect={(value, option) => this.onSelect(value, option)}
                onSearch={value => this.searchBmjc(value)}
                placeholder="输入企业名称查询"
                optionLabelProp="text"
                onFocus={val => this.onFocus(val)}
              >
                <Input maxLength={50}
                  suffix={(
                    <Button className="search-btn" type="primary" onClick={this.onSearch.bind(this, this.state.key)} >
                      <Icon type="search" />
                    </Button>
                  )}
                />
              </AutoComplete>
            </div>
          }
        />
        {
          !this.state.status &&
          <div>
            <Error></Error>
          </div>
        }
        {
          this.state.status &&
          <section>
            <div className="search-box">
              <div className="search-box-title">
                <span>企业名片</span>输入6位开票代码或使用扫描枪扫描企业名片二维码进行开票
          </div>
              {
                !this.state.hasData &&
                <div className='hasNoData'>
                  <img src='//nnfw.jss.com.cn/C13E4BBB6F1645CC9847726889C6EDAD/none.jpg' alt="" />
                  <p>
                    未找到相关的内容
                  </p>
                </div>
              }
              {
                this.state.hasData &&
                <div className="search-box-res">
                  <div className="search-box-res-qrcode">
                    <QRCode value={this.state.qrcode} size={this.state.size} renderAs='canvas' />
                    <p>
                      开票代码：{this.state.kpdm}
                    </p>
                  </div>

                  <div className="search-box-res-text">
                    {
                      !this.state.isedit &&
                      <div>
                        <div className="tiem">
                          <span className='title'>企业名称：</span>
                          <span className='desp'>{this.state.form.ckpname}</span>
                        </div>
                        <div className="tiem">
                          <span className='title'>企业税号：</span>
                          <span className='desp'>{this.state.form.ckpcode}</span>
                        </div>
                        <div className="tiem">
                          <span className='title'>注册地址：</span>
                          <span className='desp'>{this.state.form.ckpaddr}</span>
                        </div>
                        <div className="tiem">
                          <span className='title'>注册电话：</span>
                          <span className='desp'>{this.state.form.ckptel}</span>
                        </div>
                        <div className="tiem">
                          <span className='title'>开户银行：</span>
                          <span className='desp'>{this.state.form.caccountBlank}</span>
                        </div>
                        <div className="tiem">
                          <span className='title'>开户账号：</span>
                          <span className='desp'>{this.state.form.cbankAccount}</span>
                        </div>
                        <div className='edit'>
                          <Button type="primary" onClick={this.edit.bind(this, true)}>编辑</Button>
                        </div>
                      </div>
                    }

                    {
                      this.state.isedit &&
                      <div>
                        <Form onSubmit={this.handleSubmit}>
                          <Form.Item
                            {...formItemLayout}
                            label="企业名称："
                            className='item'
                          >
                            {getFieldDecorator('ckpname', {
                              initialValue: this.state.form && this.state.form.ckpname,
                              rules: [{ required: true, message: '请输入企业名称' }, { min: 2, message: '不能少于2个字符' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" maxLength={50} autoCorrect="off" spellCheck="false" type="text" placeholder="请输入企业名称" />

                            )}
                          </Form.Item>
                          <Form.Item
                            {...formItemLayout}
                            label="企业税号："
                          >
                            {getFieldDecorator('ckpcode', {
                              initialValue: this.state.form && this.state.form.ckpcode,
                              rules: [{ required: true, message: '请输入企业税号' }, { pattern: /^[a-zA-Z0-9]{15,20}$/, message: '请输入正确的企业税号' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={20} placeholder="请输入企业税号" />

                            )}
                          </Form.Item>
                          <Form.Item
                            {...formItemLayout}
                            label="注册地址："
                          >
                            {getFieldDecorator('ckpaddr', {
                              initialValue: this.state.form && this.state.form.ckpaddr,
                              rules: [{ min: 6, message: '请输入完整的注册地址信息' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={60} placeholder="请输入注册地址" />

                            )}
                          </Form.Item>
                          <Form.Item
                            {...formItemLayout}
                            label="注册电话："
                          >
                            {getFieldDecorator('ckptel', {
                              initialValue: this.state.form && this.state.form.ckptel,
                              rules: [{ min: 6, message: '请输入正确的注册电话' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={20} placeholder="请输入注册电话" />

                            )}
                          </Form.Item>
                          <Form.Item
                            {...formItemLayout}
                            label="开户银行："
                          >
                            {getFieldDecorator('caccountBlank', {
                              initialValue: this.state.form && this.state.form.caccountBlank,
                              rules: [{ min: 2, message: '请输入开户银行' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={40} placeholder="请输入开户银行" />

                            )}
                          </Form.Item>
                          <Form.Item
                            {...formItemLayout}
                            label="开户账号："
                          >
                            {getFieldDecorator('cbankAccount', {
                              initialValue: this.state.form && this.state.form.cbankAccount,
                              rules: [{ min: 6, message: '请输入完整的开户账号' }, { pattern: /^\d{6,25}$/, message: '开户账号不能含有特殊字符' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={25} placeholder="请输入开户账号" />

                            )}
                          </Form.Item>

                          <Form.Item
                            className='inline'
                            labelCol={{ span: 9 }}
                            wrapperCol={{ span: 14 }}
                            label="手机号码："
                          >
                            {getFieldDecorator('phone', {
                              rules: [{ required: true, 'message': '请填写手机号码' }, { pattern: /^(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '请输入正确的手机号' }],
                            })(
                              <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={11} placeholder="手机号码" />

                            )}
                          </Form.Item>
                          <Form.Item
                            className='inline code'
                            labelCol={{ span: 9 }}
                            wrapperCol={{ span: 15 }}
                            label="短信验证码："
                          >
                            {getFieldDecorator('yzmCode', {
                              // initialValue: this.state.form && this.state.form.phone,
                              rules: [{ required: true, 'message': '请填写短信验证码' }, { pattern: /^\d{6}$/, message: '请输入正确的短信验证码' }],
                            })(
                              <div>

                                <Input size="large" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" type="text" maxLength={6} placeholder="验证码" />
                                <span onClick={this.getMsgCode} disabled={this.state.msgYzmdis}>{this.state.dlgTipTxt}</span>
                              </div>
                            )}
                          </Form.Item>
                          <Form.Item
                            className='inline button'
                          >
                            <Popconfirm placement="top" title='您确定要取消吗？' onConfirm={() => this.cancelEdit()} okText="确定" cancelText="取消">
                              <Button type="" size='large'>取消</Button>
                            </Popconfirm>
                            <Button type="primary" htmlType="submit" size='large'>提交</Button>
                          </Form.Item>
                        </Form>
                      </div>
                    }
                  </div>
                </div>
              }
            </div>
            <Footer></Footer>
          </section>

        }
      </div>
    )
  }
}
const search = Form.create()(searchFn)

export default search